#include <winsock2.h>
#include <ballade/util/func.h>
#include <ballade/network/input_stream.h>

namespace Ballade
{
	namespace Network
	{
		
		// Constructor/Deconstructor
		InputStream::InputStream() {}
		
		InputStream::InputStream(const int sock)
		{
			_sock = sock;
		}
		
		InputStream::~InputStream()
		{
			Logger_.close();
		}
		// End of Constructor/Deconstructor
		
		// Public
		const int InputStream::read(char *buf, const int len) const
		{
			int rlen = ::recv(_sock, buf, len, 0);
			
			int error = WSAGetLastError();
			if(rlen == 0 ||
				error == WSAECONNRESET || 
				error == WSAENOTCONN)
			{
				throw SocketError("Recv data failed");
			}
			
			if(rlen > 0)
			{
				if(Logger_.isDebugEnabled())
				{
					char *buf_ = new char[rlen*12];
					memset(buf_, 0x00, rlen*12);
					Util::repr(buf_, buf, rlen);
					Logger_.debug("InputStream(Read) - Bytes received: %d, Raw data: %s", rlen, buf_);
					delete [] buf_;
				}
			}
			
			return rlen;
		}
		// End of Public
		
		// Static
		Util::Logger &InputStream::Logger_ = Util::Logger::getInstance();
		// End of Static

	}
}